import { EventEmitter } from 'events';
import * as https from 'https';
import * as http from 'http';

// 消息类型定义
export interface Message {
    sender: 'user' | 'agent';
    content: string;
    timestamp: Date;
}

export class ChatManager extends EventEmitter {
    private _messages: Message[] = [];

    constructor() {
        super();
    }

    // 添加消息
    addMessage(sender: 'user' | 'agent', content: string) {
        const message: Message = {
            sender,
            content,
            timestamp: new Date()
        };
        
        this._messages.push(message);
        this.emit('messagesUpdated');
    }

    // 移除最后一条消息（用于清除"正在思考"状态）
    removeLastMessage() {
        if (this._messages.length > 0) {
            this._messages.pop();
            this.emit('messagesUpdated');
        }
    }

    // 获取所有消息
    getMessages(): Message[] {
        return [...this._messages];
    }

    // 注册消息更新监听器
    onMessagesUpdated(callback: () => void) {
        this.on('messagesUpdated', callback);
    }

    // 模拟AI响应
    getAIResponse(userMessage: string): string {
        // 简单的模拟回复逻辑
        const responses = [
            `我理解你说的"${userMessage}"。这是一个很有趣的话题。`,
            `关于"${userMessage}"，我可以提供更多相关信息。你想了解哪方面的内容呢？`,
            `你提到了"${userMessage}"，这让我想到了一些相关的概念。需要我详细解释一下吗？`,
            `对于"${userMessage}"这个问题，我的看法是...`,
            `感谢你分享"${userMessage}"。从我的角度来看...`
        ];
        
        // 随机选择一个回复
        return responses[Math.floor(Math.random() * responses.length)];
    }

    // 调用AI API获取响应
    async getAIResponseFromAPI(userMessage: string): Promise<string> {
        const postData = JSON.stringify({
            prompt: userMessage
        });

        const options = {
            hostname: 'localhost',
            port: 8000,
            path: '/chat',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        return new Promise((resolve) => {
            const req = http.request(options, (res) => {
                let data = '';
                
                res.on('data', (chunk) => {
                    data += chunk;
                });
                
                res.on('end', () => {
                    try {
                        const result = JSON.parse(data);
                        resolve(result.response);
                    } catch (error) {
                        console.error('Error parsing API response:', error);
                        resolve('抱歉，我无法理解AI的回复。请稍后再试。');
                    }
                });
            });

            req.on('error', (error) => {
                console.error('Error calling AI API:', error);
                resolve('抱歉，我无法连接到AI服务。请稍后再试。');
            });

            req.write(postData);
            req.end();
        });
    }
    
    // 调用AI API获取响应
    async getAIResponseFromRZ(userMessage: string): Promise<string> {
        const postData = JSON.stringify({
            userInfo: {
                userld: '1',
                appld: 'test01',
                businessld: '1',
                orgld: '1',
                channelId: '1'
            },
            domainCode: '141755134770948',
            version: '1.0',
            promptParams: [
                {
                    key: 'text',
                    value: userMessage
                }
            ]
        });

        const options = {
            hostname: '10.0.131.90',
            port: 80,
            path: '/api/domain/call/141755134770948',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'token': 'FzL3vvXbXUwe9HKYENtyETv36c3Rr0i3',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        return new Promise((resolve) => {
            const req = http.request(options, (res) => {
                let data = '';
                
                res.on('data', (chunk) => {
                    data += chunk;
                });
                
                res.on('end', () => {
                    try {
                        const result = JSON.parse(data);
                        if (result.code === 1 && result.data && result.data.content) {
                            resolve(result.data.content);
                        } else {
                            console.error('API returned error:', result.message || 'Unknown error');
                            resolve('抱歉，AI服务返回了错误。请稍后再试。');
                        }
                    } catch (error) {
                        console.error('Error parsing API response:', error);
                        resolve('抱歉，我无法理解AI的回复。请稍后再试。');
                    }
                });
            });

            req.on('error', (error) => {
                console.error('Error calling AI API:', error);
                resolve('抱歉，我无法连接到AI服务。请稍后再试。');
            });

            req.write(postData);
            req.end();
        });
    }
}